package dm.ass2.item.io;
/**
 * 
 */


import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Writable;

import dm.ass2.user.io.CBElement;

/**
 * @author yaron
 *
 */
public class ItemMapOutputValueWritable implements Writable {
	/**
	 * array of users assigned to the user-cluster.
	 */
	private int[] usersList;
	
	/**
	 * an array of {@link CBElement} - the i'th element contains 
	 * the number of items in the current user profile which belong 
	 * to item-cluster i, and the sum of ratings of these items. 
	 */
	private CBElement[] cbElements;

	public ItemMapOutputValueWritable() {
		
	}
	
	/**
	 * Constructor
	 * 
	 * @param usersList
	 * @param cbElements
	 */
	public ItemMapOutputValueWritable(int[] usersList, CBElement[] cbElements) {
		super();
		this.usersList = usersList;
		this.cbElements = cbElements;
	}

	@Override
	public void readFields(DataInput in) throws IOException {
		int usersListLength = in.readInt();
		usersList = new int[usersListLength];
		for (int i = 0; i < usersList.length; i++) {
			usersList[i] = in.readInt();
		}
		
		int cbElementsLength = in.readInt();
		cbElements = new CBElement[cbElementsLength];
		for (int i = 0; i < cbElements.length; i++) {
			int ratingsCounter = in.readInt();
			float ratingsSum   = in.readFloat();
			CBElement cbElement = new CBElement(ratingsCounter, ratingsSum);
			cbElements[i] = cbElement;
		}
	}

	@Override
	public void write(DataOutput out) throws IOException {

		out.writeInt(usersList.length);
		for (int i = 0; i < usersList.length; i++) {
			out.writeInt(usersList[i]);
		}

		out.writeInt(cbElements.length);

		for (int i = 0; i < cbElements.length; i++) {
			if (cbElements[i] == null) {
				out.writeInt(0);
				out.writeFloat(0);
			} else {
				out.writeInt(cbElements[i].getRatingsCounter());
				out.writeFloat(cbElements[i].getRatingsSum());
			}
		}

	}

	public int[] getUsersList() {
		return usersList;
	}

	public CBElement[] getCbElements() {
		return cbElements;
	}

}
